#include "refiner.h"

int main(int argc,char **argv)
{
  // MPI Variables and error handles
  PetscErrorCode        ierr;
  ierr = PetscInitialize(&argc, &argv, NULL, NULL); CHKERRQ(ierr);
    
  int rank,             size;
  MPI_Comm              local_comm;
  PetscBool             flag;
  int                   n_par_sims = 8;
  int                   num_refinements = 4;
  
  PetscOptionsGetInt(PETSC_NULL, "-simulations", &n_par_sims, &flag);
  PetscOptionsGetInt(PETSC_NULL, "-refinements", &num_refinements, &flag);
  
  
  MPI_Comm_rank(MPI_COMM_WORLD, &rank);
  MPI_Comm_size(MPI_COMM_WORLD, &size);
  int local_color = rank % n_par_sims;
  
  if ( size % n_par_sims == 0 ) {
    MPI_Comm_split(MPI_COMM_WORLD, local_color, 0, &local_comm);
    PetscPrintf(PETSC_COMM_SELF, "[INFO] Process %d of %d gets color %d...\n",
                rank, size, local_color);
  } else {
    PetscPrintf(PETSC_COMM_WORLD, "[ERROR] Requested %d parallel simulations onto %d processors (num. of processors must be a multiple of the num. of parallel simulations). Breaking...\n",
                n_par_sims, size);
    ierr = PetscFinalize(); CHKERRQ(ierr);
    return -1;
  }
  
  Refiner                *refiner = new Refiner(local_comm, local_color, num_refinements);
  
  ierr = refiner->run(); CHKERRQ(ierr);
  //ierr = refiner->compute_error(); CHKERRQ(ierr);
  //ierr = refiner->save_error(); CHKERRQ(ierr);
  //ierr = refiner->save_runtime(); CHKERRQ(ierr);
  //ierr = refiner->save_report(); CHKERRQ(ierr);
  
  delete refiner;
  
  ierr = PetscFinalize(); CHKERRQ(ierr);
  
  return 0;
}
